# pip install pyjwt
import jwt
from datetime import datetime, timedelta, timezone

# 加密盐值
salt = "khfHbganlhjVRN"


# 获取token
async def get_token(user_id: str):
    # payload 加密体
    payload = {
        'user_id': user_id,
        'exp': datetime.now(timezone.utc) + timedelta(hours=10)
    }
    # header为可选，默认即为一下内容，如需修改加密算法，可以设置该内容
    header = {
        'alg': 'HS256',
        'typ': 'jwt'
    }
    token = jwt.encode(payload=payload, key=salt, headers=header)
    # print(token)
    return token


# 获取token
async def get_pc_token(data):
    # payload 加密体
    payload = {
        'data': data,
        'exp': datetime.now(timezone.utc) + timedelta(hours=10)
    }
    # header为可选，默认即为一下内容，如需修改加密算法，可以设置该内容
    header = {
        'alg': 'HS256',
        'typ': 'jwt'
    }
    token = jwt.encode(payload=payload, key=salt, headers=header)
    # print(token)
    return token


# 验证token
async def verify_token(token):
    payload = None
    msg = None
    try:
        payload = jwt.decode(token, salt, algorithms="HS256")
    except jwt.exceptions.DecodeError:
        msg = '认证失败'
    except jwt.exceptions.ExpiredSignatureError:
        msg = '签名过期'
    except jwt.exceptions.InvalidAlgorithmError:
        msg = '无效算法错误'

    if payload:
        # print(payload)
        return payload
    else:
        # print(msg)
        return False
